package tiku_handler

import (
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"net/http"
	"peilian-api/app/global/bind"
	"peilian-api/app/global/databases/tables"
	"peilian-api/app/global/errors"
	"peilian-api/app/global/variable"
	"peilian-api/app/model"
	"peilian-api/app/services/tiku_service"
	"peilian-api/utils/format"
	"peilian-api/utils/tools"
	"strings"
)

func GetTikuList(ctx *gin.Context) {
	var tlq model.TikuListReq
	if err := bind.ShouldBinding(ctx, &tlq); err != nil {
		format.NewResponseJson(ctx).Err(errors.PublicErrorCode, errors.ParamBindError)
		return
	}
	count, out, err := new(tiku_service.TikuService).GetTIkuList(ctx, tlq)
	if err != nil {
		format.NewResponseJson(ctx).Err(err.Code, err.Err.Error())
		return
	}
	format.NewResponseJson(ctx).SuccessDataList(int(count), out)
}

func UpdateTikuList(ctx *gin.Context) {
	var tlu tables.Question
	if err := bind.ShouldBinding(ctx, &tlu); err != nil {
		format.NewResponseJson(ctx).ErrObj(errors.PublicErrorCode, errors.ParamBindError)
		return
	}
	if tlu.AnsAnalysis != "" {
		formatAnsAnalysis := []string{tlu.AnsAnalysis}
		jsonStr, _ := json.Marshal(formatAnsAnalysis)
		tlu.AnsAnalysis = string(jsonStr)

	}
	if tlu.ProfessionId != nil {
		p, err := tables.GetProfessionById(*tlu.ProfessionId)
		if err != nil || p.ID == 0 {
			format.NewResponseJson(ctx).Err(http.StatusBadRequest, "Profession 未获取到")
			return
		}
		tlu.Profession = p
	}
	err := new(tiku_service.TikuService).UpdateTikuList(ctx, &tlu)
	if err != nil {
		format.NewResponseJson(ctx).ErrObj(err.Code, err.Err.Error())
		return
	}
	format.NewResponseJson(ctx).SuccessObj(&tlu)
}

func DeleteTikuList(ctx *gin.Context) {
	question_id := ctx.Param("id")
	uid, exists := ctx.Get("uid")
	if !exists {
		format.NewResponseJson(ctx).Err(30001, "您无权操作")
		return
	}
	Que := tables.Question{}
	d := variable.DB.MySQL.Where("id = ?", question_id).Find(&Que)
	if d.RowsAffected == 0 {
		format.NewResponseJson(ctx).Err(30001, "问题不存在")
		return
	}

	var customCareers []tables.CustomCareer
	err := variable.DB.MySQL.Model(&tables.CustomCareer{}).Where(
		"question_id=?", question_id).Preload("Career").Find(&customCareers).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		format.NewResponseJson(ctx).Err(30001, fmt.Sprintf("获取关联信息失败:%+v", err))
		return
	}
	var names []string
	for _, c := range customCareers {
		if c.Career != nil && c.Career.Name != "" {
			names = append(names, c.Career.Name)
		}
	}
	if len(names) > 0 {
		format.NewResponseJson(ctx).Err(30001, fmt.Sprintf("有职业正在使用该问题：%s", strings.Join(names, ",")))
		return
	}

	user, err := tables.GetUserInfoById(int(uid.(uint)))
	if err != nil {
		format.NewResponseJson(ctx).Err(30001, "用户信息获取失败")
		return
	}

	if Que.Source == 1 && user.Level != 1 {
		format.NewResponseJson(ctx).Err(30001, "不能删除系统内置问题")
		return
	}
	variable.DB.MySQL.Delete(&tables.Question{}, "id=?", question_id)
	format.NewResponseJson(ctx).SuccessObj(struct{}{})
}

func AddTikuList(c *gin.Context) {
	var question tables.Question
	if err := c.ShouldBindJSON(&question); err != nil {
		format.NewResponseJson(c).Err(30001, err.Error())
		return
	}
	uid, exists := c.Get("uid")
	if !exists {
		format.NewResponseJson(c).Err(30001, "您无权操作")
		return
	}
	if tools.HanZiLen(question.Text) > 100 {
		format.NewResponseJson(c).Err(30001, "题目内容不能超过100个字")
		return
	}
	question.User_id = uid.(uint)
	if len(question.SkillTagIds) > 3 || len(question.SkillTagIds) <= 0 {
		format.NewResponseJson(c).Err(http.StatusBadRequest, "能力标签为1-3个")
		return
	}
	if question.ProfessionId != nil {
		p, err := tables.GetProfessionById(*question.ProfessionId)
		if err != nil || p.ID == 0 {
			format.NewResponseJson(c).Err(http.StatusBadRequest, "Profession 未获取到")
			return
		}
		question.Profession = p
	}
	if err := variable.DB.MySQL.Transaction(func(tx *gorm.DB) error {
		question.Source = 2 // 调接口为自定义题目
		formatAnsAnalysis := []string{question.AnsAnalysis}
		jsonStr, _ := json.Marshal(formatAnsAnalysis)
		question.AnsAnalysis = string(jsonStr)
		_ = question.SetCustomKeyWords()
		if err := variable.DB.MySQL.Create(&question).Error; err != nil {
			return err
		}
		//fmt.Println(question.SkillTagIds)
		TagQuestionLi := make([]*tables.CriteriaRelation, 0)
		for _, tagId := range question.SkillTagIds {
			TagQuestionLi = append(TagQuestionLi, &tables.CriteriaRelation{
				QuestionID: question.ID,
				CriteriaID: tagId,
			})
		}
		if err := variable.DB.MySQL.Create(&TagQuestionLi).Error; err != nil {
			return err
		}
		return nil
	}); err != nil {
		format.NewResponseJson(c).Err(http.StatusInternalServerError, err.Error())
		return
	}
	//新创建一个问题，需要生成视频
	go func() {
		err := new(tiku_service.TikuService).GenerateVideo(c, question.ID, "")
		if err != nil {
			format.NewResponseJson(c).ErrObj(err.Code, err.Err.Error())
			return
		}
	}()
	format.NewResponseJson(c).SuccessObj(&question)
}

// AddDiscussionTiku 增加圆桌讨论的问题
func AddDiscussionTiku(c *gin.Context) {
	var question tables.Question
	if err := c.ShouldBindJSON(&question); err != nil {
		format.NewResponseJson(c).Err(30001, err.Error())
		return
	}
	question.User_id = 0
	if len(question.SkillTagIds) > 3 || len(question.SkillTagIds) <= 0 {
		format.NewResponseJson(c).Err(http.StatusBadRequest, "能力标签为1-3个")
		return
	}
	if question.ProfessionId != nil {
		p, err := tables.GetProfessionById(*question.ProfessionId)
		if err != nil || p.ID == 0 {
			format.NewResponseJson(c).Err(http.StatusBadRequest, "Profession 未获取到")
			return
		}
		question.Profession = p
	}
	if err := variable.DB.MySQL.Transaction(func(tx *gorm.DB) error {
		question.Source = 3 // 调接口为自定义题目
		formatAnsAnalysis := []string{question.AnsAnalysis}
		jsonStr, _ := json.Marshal(formatAnsAnalysis)
		question.AnsAnalysis = string(jsonStr)
		_ = question.SetCustomKeyWords()
		// 配置所有的问题视频假地址，
		question.VideoStatus = 1
		question.Video = "--"
		question.PcVideo = "--"
		if err := variable.DB.MySQL.Create(&question).Error; err != nil {
			return err
		}
		//fmt.Println(question.SkillTagIds)
		TagQuestionLi := make([]*tables.CriteriaRelation, 0)
		for _, tagId := range question.SkillTagIds {
			TagQuestionLi = append(TagQuestionLi, &tables.CriteriaRelation{
				QuestionID: question.ID,
				CriteriaID: tagId,
			})
		}
		if err := variable.DB.MySQL.Create(&TagQuestionLi).Error; err != nil {
			return err
		}
		return nil
	}); err != nil {
		format.NewResponseJson(c).Err(http.StatusInternalServerError, err.Error())
		return
	}
	// 关联
	variable.DB.MySQL.Where("career_id=?", question.CareerID).Delete(&tables.CustomCareer{})
	var linkLi = tables.CustomCareer{
		CareerID:   question.CareerID,
		QuestionID: question.ID,
		Tag:        1,
	}
	if err := variable.DB.MySQL.Create(&linkLi).Error; err != nil {
		format.NewResponseJson(c).Err(http.StatusInternalServerError, err.Error())
		return
	}
	////新创建一个问题，需要生成视频
	//go func() {
	//	err := new(tiku_service.TikuService).GenerateVideo(c, question.ID, "")
	//	if err != nil {
	//		format.NewResponseJson(c).ErrObj(err.Code, err.Err.Error())
	//		return
	//	}
	//}()
	format.NewResponseJson(c).SuccessObj(&question)
}

func GetTikuItem(ctx *gin.Context) {
	id := ctx.Param("id")
	var question tables.QuestionResp
	if err := variable.DB.MySQL.Model(&tables.Question{}).Preload("Profession").Where("id=?", id).First(&question).Error; err != nil {
		format.NewResponseJson(ctx).Err(30001, err.Error())
		return
	}
	question.SkillTagIds = make([]*tables.Criteria, 0)
	if err := variable.DB.MySQL.Model(&question.Question).Association("SkillTags").Find(&question.SkillTagIds); err != nil {
		format.NewResponseJson(ctx).Err(http.StatusBadRequest, err.Error())
		return
	}
	format.NewResponseJson(ctx).SuccessObj(question)
}

// 重新生成视频
func ReGegenerateVideo(c *gin.Context) {
	var gvr model.GenerateVideoReq
	if err := bind.ShouldBinding(c, &gvr); err != nil {
		format.NewResponseJson(c).ErrObj(errors.PublicErrorCode, errors.ParamBindError)
		return
	}
	err := new(tiku_service.TikuService).GenerateVideo(c, gvr.Id, gvr.Text)
	if err != nil {
		format.NewResponseJson(c).ErrObj(err.Code, err.Err.Error())
		return
	}
	format.NewResponseJson(c).SuccessObj(struct{}{})
}
